package com.tianpengtech.admin.dictionary;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.admin.AbstractAdmin;
import com.tianpengtech.common.model.account.Account;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.search.LikeCondition;
import com.tianpengtech.common.search.QueryConstructor;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.numberic.NumbericMustBeGreaterEqualThan;
import com.tianpengtech.common.validator.rules.numberic.NumbericMustBeGreaterThan;
import com.tianpengtech.common.validator.rules.other.MustBeNull;
import com.tianpengtech.common.validator.rules.string.StringLengthBetween;
import com.tianpengtech.common.validator.rules.string.StringMustBeEmail;
import com.tianpengtech.common.validator.rules.string.StringMustBeMobile;
import com.tianpengtech.common.validator.rules.string.StringMustBeRequired;
import org.apache.commons.lang.StringUtils;

public class DictionaryAdminServiceImpl extends AbstractAdmin{

	@Override
	public void beforeAdd(Model<?> model) throws ValidateException {

		Dictionary dictionary = DictionaryDao.ME.readDirecotryByCode(model.getInt(Dictionary.CODE));
		Validator validator = new Validator();
		validator.addRule(new MustBeNull(dictionary,"当前代码已经存在了"));
		validator.addRule(new StringLengthBetween(model.getStr(Dictionary.NAME),"数据字典的名称只能输入1-50个字符信息",1,50));
		validator.addRule(new StringLengthBetween(model.getStr(Dictionary.REMARK),"数据字典的名称只能输入1-150个字符信息",1,150));
		validator.addRule(new NumbericMustBeGreaterEqualThan(model.getInt(Dictionary.CODE),0,"请选择父级分类"));
		validator.excute();
	}

	@Override
	public void beforeQueryById(Model<?> model, int id) {

	}

	@Override
	public void beforeUpdate(Model<?> model) throws ValidateException {
		Validator validator = new Validator();
		validator.addRule(new StringLengthBetween(model.getStr(Dictionary.NAME),"数据字典的名称只能输入1-50个字符信息",1,50));
		validator.addRule(new StringLengthBetween(model.getStr(Dictionary.REMARK),"数据字典的名称只能输入1-150个字符信息",1,150));
		validator.addRule(new NumbericMustBeGreaterEqualThan(model.getLong(Dictionary.CODE),0,"请选择父级分类"));
		validator.addRule(new NumbericMustBeGreaterThan(model.getInt(Account.ID), 0, "ID必须大于零"));
		validator.excute();
	}

	@Override
	public void beforeDelete(Model<?> model) {

	}

	@Override
	public void builderSQLExpected(Model< ? > model,
			QueryConstructor queryConstruct, Map< String, Object > params) {

		if(StringUtils.isNotEmpty(model.getStr(Dictionary.NAME))){
			queryConstruct.and(new LikeCondition(Dictionary.NAME,"%"+model.getStr(Dictionary.NAME)+"%"));
		}
	}

	@Override
	public String tableName() {
		return Dictionary.dao.tableName();
	}

}